#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "filereader.h"

static int getfilesize(FILE *file) {
        int size;
        fseek(file, 0, SEEK_END);
        size = ftell(file);
        fseek(file, 0, SEEK_SET); // seek back to beginning of file
        return size;
}

void fileread(struct afile *f, const char *filename) {
        FILE *file;
        file = fopen(filename, "r");
        if(file == NULL) {
                perror("fopen");
                return;
        }

        // get the file size so that we can allocate the array
        int size = getfilesize(file);

        char *buffer = malloc(size);
        if(buffer == NULL) {
                perror("malloc");
                return;
        }
        memset(buffer, 0, size);

        // read file contents into buffer
        fread(buffer, size, 1, file);
        fclose(file);

        // assign to struct
        f->filesize = size;
        f->filecontents = buffer;

} 

void filecleanup(struct afile *f) {
        free(f->filecontents);
}
